﻿using System;
using System.Reflection;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Runtime.InteropServices;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

using ipi.MCC.Controls;
using ipi.MCC.Global;

namespace ipi.MCC.CustomFieldTypes
{
    public class MCCTreePositionFieldEditControl : System.Web.UI.UserControl, Microsoft.SharePoint.WebControls.IFieldEditor
    {
        protected MCCTreeStartPositionControl tspMain;
        protected CustomValidator validGlobal;
        protected InputFormControl ifcTreePositionFieldEdit;

        protected string sStartNodeID;
        
        protected override void CreateChildControls()
        {

        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                ifcTreePositionFieldEdit.LabelText = Resources.Resources.MCCTreePositionFieldEditControl_LabelText;
            }
            catch (Exception exc)
            {
                validGlobal.ErrorMessage = Exceptions.HandleException(exc, this.GetType(), MethodBase.GetCurrentMethod(), LoggingType.Exception);
                validGlobal.IsValid = false;
            }
        }

        #region IFieldEditor Members

        public bool DisplayAsNewSection
        {
//            get { throw new Exception("The method or operation is not implemented."); }
            get { return false;  }
        }

        public void InitializeWithField(SPField field)
        {
            try
            {

                MCCTreePositionField tpfCurrent = (MCCTreePositionField)field;

                if (tpfCurrent != null)
                {
                    this.EnsureChildControls();

                    sStartNodeID = tpfCurrent.StartNode;

                    if (!string.IsNullOrEmpty(sStartNodeID))
                    {
                        tspMain.PreSelectNode(sStartNodeID);
                    }
                }
            }
            catch (Exception exc)
            {
                validGlobal.ErrorMessage = Exceptions.HandleException(exc, this.GetType(), MethodBase.GetCurrentMethod(), LoggingType.Exception);
                validGlobal.IsValid = false;
            }
        }

        public void OnSaveChange(SPField field, bool isNewField)
        {
            try
            {
                MCCTreePositionField tpfCurrent = (MCCTreePositionField)field;

                if (tpfCurrent != null)
                {
                    tpfCurrent.StartNode = tspMain.GetStartNodeID().ToString();
                }
            }
            catch (Exception exc)
            {
                validGlobal.ErrorMessage = Exceptions.HandleException(exc, this.GetType(), MethodBase.GetCurrentMethod(), LoggingType.Exception);
                validGlobal.IsValid = false;
            }
        }

        #endregion
    }
}
